package com.guoguo.websocketdemo.websocketdemo.service;

import org.apache.logging.slf4j.SLF4JLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;

@Component
@ServerEndpoint("/webSocket")
public class WebSocket {

    private static final Logger log = LoggerFactory.getLogger(WebSocket.class);

    private Session session;
    private static CopyOnWriteArrayList<WebSocket> webSocketSet =
            new CopyOnWriteArrayList<WebSocket>();

    @OnOpen
    public void opOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        log.info("【websocket消息】有新的连接，总数：{}", webSocketSet.size());
    }

    @OnClose
    public void opClose() {
        webSocketSet.remove(this);
        log.info("【websocket消息】连接断开，总数：{}", webSocketSet.size());
    }

    @OnMessage
    public void opMessage(String message) {
        log.info("【websocket消息】收到客户端消息：{}", message);
    }

    // 发送消息
    public void sendMessage(String message) {
        for (WebSocket webSocket : webSocketSet){
            log.info("【websocket消息】广播消息：{}", message);
            try{
                webSocket.session.getBasicRemote().sendText(message);
            }catch (Exception e){
                log.error(e.getMessage());
            }
        }
    }
}
